#!/sbin/openrc-run

CONF="${SVCNAME#*.}"
CONFBASE="/etc/conf.d/memcached"

[ -z "${PIDBASE}" ] && PIDBASE="/run/memcached/memcached"
[ "${CONF}" = "memcached" ] && CONF=''

if [ -n "${CONF}" ]; then
    PIDFILE="${PIDBASE}.${CONF}.pid"
    CONFSRC="${CONFBASE}.${CONF}"
    if [ -f "${CONFSRC}" ]; then
        source "${CONFSRC}"
    else
        eerror "The configuration file $CONFSRC was not found!"
    fi
else
    PIDFILE="${PIDBASE}.pid"
    CONFSRC="${CONFBASE}"
fi

depend() {
    # per bug #269022, accurate time is important for memcached!
    # We include the full list of ways it might be set on boot.
    after ntp-client ntpd rdate openrdate adjtimex hwclock
}

checkconfig() {
    if [ -z "${LISTENON}" ] && [ -z "${SOCKET}" ]; then
        ewarn "You should edit $CONFSRC and specify an address or socket to listen on."
        ewarn "Listening on any address (check your firewall!)"
    fi
}

start() {
    if [ -n "${CONF}" ]; then
        ebegin "Starting memcached (${CONF})"
    else
        ebegin "Starting memcached"
    fi
    checkconfig
    local dir="$(dirname ${PIDFILE})"
    if [ ! -d "${dir}" ]; then
        einfo " Creating ${dir}"
        mkdir -p "${dir}"
    fi

    chown ${MEMCACHED_RUNAS} "${dir}"
    if [ -f "${PIDFILE}" ]; then
        einfo "  Removing stale pidfile ${PIDFILE}"
        rm -f "${PIDFILE}" 1>/dev/null
    fi

        
    if [ -n "${SOCKET}" ]; then
        CONNECTION="-s ${SOCKET}"

        if [ -n "${SOCKET_MASK}" ]; then
            CONNECTION="${CONNECTION} -a ${SOCKET_MASK}"
        fi
    else
        CONNECTION="-p ${PORT} -U ${UDPPORT}"

        if [ -n "${LISTENON}" ]; then
            CONNECTION="${CONNECTION} -l ${LISTENON}"
        fi
    fi

    /sbin/start-stop-daemon --start --pidfile "${PIDFILE}" \
        --exec "${MEMCACHED_BINARY}" -- \
        -d ${CONNECTION} -m ${MEMUSAGE}  \
        -c ${MAXCONN} -u ${MEMCACHED_RUNAS} -P "${PIDFILE}" \
        ${MISC_OPTS}

    eend $?
}

stop() {
    if [ -n "${CONF}" ]; then
        ebegin "Stopping memcached (${CONF})"
    else
        ebegin "Stopping memcached"
    fi

    start-stop-daemon --stop --quiet --pidfile "${PIDFILE}"

    rm -f "${PIDFILE}"

    eend $?
}
